package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.CommentMapper;
import edu.sdbi.judge.mapper.VisitMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.ErrorUtil;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.*;

@Order(13)
@Service
public class Judge_13 implements GetJudgeIpResultService {
    @Autowired
    private HttpUtil httpUtil;

    @Value("${test.newsIds:1,2}")
    private String newsIds;
    @Autowired
    private VisitMapper visitMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("13");

        try {
            // 直接使用配置中的newsID，无需数据库查询
            String url = "http://" + ip + "/statistics/compare";

            // 封装请求参数，使用配置中的newsID
            Map<String, String> params = new HashMap<>();
            params.put("newIds", newsIds);

            // 发送HTTP请求
            String resultStr = httpUtil.doGet(url, null, params);
            studentResult.setResult(resultStr);

            // 验证返回结果
            JsonResult jsonResult = JSONObject.parseObject(resultStr, JsonResult.class);
            if (jsonResult.getCode() == 200) {
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) jsonResult.getData();
                if (validateResponseData(dataList)) {
                    studentResult.setScore(4.0); // 完全符合要求得4分
                    studentResult.setComment("测试通过：返回数据格式和内容正确");
                } else {
                    studentResult.setScore(0.0);
                    studentResult.setComment("返回数据格式或内容不符合要求");
                }
            } else {
                studentResult.setScore(0.0); // 明确设置分数为0
                studentResult.setComment("接口返回错误：" + jsonResult.getMsg());
            }

        } catch (Exception e) {
            e.printStackTrace();
            studentResult.setScore(0.0); // 异常情况下设置分数为0
            studentResult.setResult(ErrorUtil.stackTraceToString(e));
            studentResult.setComment("执行测试时发生异常：" + e.getMessage());
        }
        return studentResult;
    }

    private boolean validateResponseData(List<Map<String, Object>> dataList) {
        // 检查数据是否为空
        if (dataList == null || dataList.isEmpty()) {
            return false;
        }

        // 检查是否包含所有请求的新闻ID
        Set<String> requestedIds = new HashSet<>(Arrays.asList(newsIds.split(",")));

        for (Map<String, Object> news : dataList) {
            news.put("newsId", news.get("newsid"));
            // 检查每条新闻是否包含必要字段
            if (!news.containsKey("newsId") ||
                    !news.containsKey("title") ||
                    !news.containsKey("visitsCount") ||
                    !news.containsKey("commentCount")) {
                return false;
            }

            // 检查字段类型是否正确
            Object newsIdObj = news.get("newsId");
            Object visitsCountObj = news.get("visitsCount");
            Object commentCountObj = news.get("commentCount");

            if (!(newsIdObj instanceof String) ||
                    !(visitsCountObj instanceof Integer) ||
                    !(commentCountObj instanceof Integer)) {
                return false;
            }

            String newsId = (String) newsIdObj;
            if (requestedIds.contains(newsId)) {
                int count = visitMapper.countByNewsId(newsId);
                int count2 = commentMapper.countCommentsByNewsId(newsId);
                if (count != (Integer) visitsCountObj || count2 != (Integer) commentCountObj) {
                    return false;
                }
                requestedIds.remove(newsId);
            }
        }
        return true;
    }
}
